package com.wyclabs.gateway.auth;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import java.util.*;

/**
 * 类注释
 * @author rs
 * @date 2019/10/29
 */
@Slf4j
public class CustomizeUserInfoTokenServices implements ResourceServerTokenServices {
    private static List<GrantedAuthority> grantedAuthorities;
    private static Set<String> scopes = new HashSet<>();

    static {
        grantedAuthorities = new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("anonymous"));
        scopes.add("server");
    }

    private RedisTokenStore redisTokenStore;

    public CustomizeUserInfoTokenServices(RedisTokenStore redisTokenStore) {
        this.redisTokenStore = redisTokenStore;
    }

    @Override
    public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
        OAuth2Authentication oAuth2Authentication = redisTokenStore.readAuthentication(accessToken);
        if (oAuth2Authentication == null) {
            //构造匿名用户
            AnonymousAuthenticationToken auth = new AnonymousAuthenticationToken("wyclabs", "anonymous", grantedAuthorities);
            oAuth2Authentication = new OAuth2Authentication(new OAuth2Request(new HashMap<>(1), "anonymous", grantedAuthorities, true, scopes, null, null, null, null), auth);
        }
        return oAuth2Authentication;
    }

    @Override
    public OAuth2AccessToken readAccessToken(String accessToken) {
        return redisTokenStore.readAccessToken(accessToken);
    }

}
